<template>
  <div class="db-management">
    <div class="dir">
      <tree-aside
        v-model:selectedInfo="treeSelectedInfo"
        @ready="onReadyTree"
      />
    </div>
    <div class="detail">
      <detail-card
        :groupId="groupId"
        :treeSelectedInfo="treeSelectedInfo"
        v-if="ready"
        :staticPermission="staticPermission"
      />
    </div>
  </div>
</template>
<script setup>
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import TreeAside from './tree-aside.vue'
import DetailCard from './detail-card.vue'
/**
 * 外部参数
 */
defineProps({
  staticPermission: {
    type: Object,
  },
})

/**
 * 如果导航上有目录选中参数与关键字查询参数就需要等待树加载完毕后查询出树节点信息
 */
//keyWord 监听导航上的参数变化
let route = useRoute()
let ready = ref(false)
function findTreeSelectedInfo(tree = [], categoryid) {
  let target = tree.find(node => node.categoryId === categoryid)
  if (target) {
    return target
  } else {
    let target
    tree.forEach(node => {
      let targetCurrent = findTreeSelectedInfo(node.children, categoryid)
      if (targetCurrent) {
        target = targetCurrent
      }
    })
    return target
  }
}
function onReadyTree(tree) {
  if (route.query.categoryid) {
    let info = findTreeSelectedInfo(tree, route.query.categoryid)
    treeSelectedInfo.value = info
  }
  ready.value = true
}
let treeSelectedInfo = ref()
let groupId = computed(() => treeSelectedInfo.value?.categoryId)

function reload(event) {
  if (!event.state) {
    window.location.reload()
  }
}
onMounted(() => {
  window.addEventListener('popstate', reload)
})
onUnmounted(() => {
  window.removeEventListener('popstate', reload)
})
</script>
<script>
export default {
  name: 'db-management/project',
}
</script>
<style scoped lang="less">
.db-management {
  height: 100%;
  display: flex;
  .dir {
    background: #ffffff;
    border-radius: 2px;
    margin-right: 12px;
    padding: 20px;
    min-width: 212px;
    box-sizing: border-box;
  }
  .detail {
    flex: 1;
    overflow: hidden;
  }
}
</style>
